<template>
  <div class="services-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>服务管理</h1>
        <p>管理您发布的洗护服务，让客户更容易找到您</p>
      </div>
    </div>

    <!-- 服务统计 -->
    <el-row :gutter="20" class="stats-section">
      <el-col :span="4">
        <el-card class="stat-card draft">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ serviceStats.draft }}</div>
              <div class="stat-label">草稿箱</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stat-card pending">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ serviceStats.pending }}</div>
              <div class="stat-label">审核中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stat-card approved">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ serviceStats.approved }}</div>
              <div class="stat-label">已通过</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stat-card rejected">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Close /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ serviceStats.rejected }}</div>
              <div class="stat-label">被驳回</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stat-card active">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ serviceStats.active }}</div>
              <div class="stat-label">已上架</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stat-card revenue">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Wallet /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ serviceStats.totalRevenue.toLocaleString() }}</div>
              <div class="stat-label">总收入</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 服务列表 -->
    <el-card class="services-list-card">
      <template #header>
        <div class="card-header">
          <span>我的服务</span>
          <div class="header-filters">
            <el-select v-model="filterAuditStatus" placeholder="审核状态" style="width: 120px; margin-right: 10px;">
              <el-option label="全部" value="" />
              <el-option label="草稿箱" value="draft" />
              <el-option label="审核中" value="pending" />
              <el-option label="已通过" value="approved" />
              <el-option label="被驳回" value="rejected" />
              <el-option label="被封禁" value="banned" />
            </el-select>
            <el-select v-model="filterStatus" placeholder="上架状态" style="width: 120px; margin-right: 10px;">
              <el-option label="全部" value="" />
              <el-option label="已上架" value="active" />
              <el-option label="已下架" value="inactive" />
            </el-select>
            <el-select v-model="filterType" placeholder="类型筛选" style="width: 120px; margin-right: 10px;">
              <el-option label="全部" value="" />
              <el-option label="洗衣服" value="laundry" />
              <el-option label="洗鞋" value="shoes" />
              <el-option label="洗萌宠" value="pet" />
              <el-option label="洗包包" value="bag" />
              <el-option label="洗被子" value="bedding" />
              <el-option label="洗车" value="car" />
            </el-select>
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              发布服务
            </el-button>
          </div>
        </div>
      </template>

      <div class="services-grid">
        <div
          v-for="service in filteredServices"
          :key="service.id"
          class="service-card"
        >
          <div class="service-header">
            <div class="service-type-icon" :class="getServiceIconClass(service.type)">
              <el-icon><component :is="getServiceIcon(service.type)" /></el-icon>
            </div>
            <div class="service-status">
              <!-- 审核状态 -->
              <el-tag
                :type="getAuditStatusType(service.auditStatus)"
                size="small"
                style="margin-bottom: 4px;"
              >
                {{ getAuditStatusText(service.auditStatus) }}
              </el-tag>
              <!-- 上架状态 -->
              <el-tag
                v-if="service.auditStatus === 'approved'"
                :type="service.status === 'active' ? 'success' : 'info'"
                size="small"
              >
                {{ service.status === 'active' ? '已上架' : '已下架' }}
              </el-tag>
            </div>
          </div>

          <div class="service-content">
            <h3>{{ service.name }}</h3>
            <p class="service-description">{{ service.description }}</p>

            <div class="service-details">
              <div class="detail-item">
                <span class="label">价格：</span>
                <span class="value price">¥{{ service.price }}/{{ service.unit }}</span>
              </div>
              <div class="detail-item">
                <span class="label">服务区域：</span>
                <span class="value">{{ service.serviceArea }}</span>
              </div>
              <div class="detail-item">
                <span class="label">预计时长：</span>
                <span class="value">{{ service.duration }}小时</span>
              </div>
              <!-- 推广链接信息 -->
              <div v-if="service.linkId" class="detail-item">
                <span class="label">推广编号：</span>
                <span class="value link-id">{{ service.linkId }}</span>
              </div>
              <!-- 审核时间 -->
              <div v-if="service.auditTime" class="detail-item">
                <span class="label">审核时间：</span>
                <span class="value">{{ service.auditTime }}</span>
              </div>
            </div>

            <!-- 审核备注 -->
            <div v-if="service.auditRemark" class="audit-remark">
              <div class="remark-label">
                <el-icon><Warning /></el-icon>
                <span>审核意见：</span>
              </div>
              <div class="remark-content">{{ service.auditRemark }}</div>
            </div>

            <div class="service-stats">
              <div class="stat-item">
                <span class="stat-number">{{ service.orderCount || 0 }}</span>
                <span class="stat-text">订单</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ service.rating || 5.0 }}</span>
                <span class="stat-text">评分</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">¥{{ service.revenue || 0 }}</span>
                <span class="stat-text">收入</span>
              </div>
            </div>
          </div>

          <div class="service-actions">
            <!-- 草稿状态 -->
            <template v-if="service.auditStatus === 'draft'">
              <el-button size="small" @click="editService(service)">编辑</el-button>
              <el-button size="small" type="primary" @click="submitForReview(service)">提交审核</el-button>
              <el-button size="small" type="danger" @click="deleteService(service)">删除</el-button>
            </template>

            <!-- 审核中状态 -->
            <template v-else-if="service.auditStatus === 'pending'">
              <el-button size="small" @click="viewService(service)">查看</el-button>
              <el-button size="small" type="warning" @click="withdrawReview(service)">撤回审核</el-button>
            </template>

            <!-- 被驳回状态 -->
            <template v-else-if="service.auditStatus === 'rejected'">
              <el-button size="small" @click="editService(service)">重新编辑</el-button>
              <el-button size="small" type="primary" @click="submitForReview(service)">重新提交</el-button>
              <el-button size="small" type="danger" @click="deleteService(service)">删除</el-button>
            </template>

            <!-- 已通过状态 -->
            <template v-else-if="service.auditStatus === 'approved'">
              <el-button size="small" @click="editService(service)">编辑</el-button>
              <el-button
                size="small"
                :type="service.status === 'active' ? 'warning' : 'success'"
                @click="toggleStatus(service)"
              >
                {{ service.status === 'active' ? '下架' : '上架' }}
              </el-button>
              <el-button size="small" type="primary" @click="goToPromotion(service)">推广管理</el-button>
              <el-button size="small" type="info" @click="moveToDraft(service)">退回草稿</el-button>
            </template>

            <!-- 被封禁状态 -->
            <template v-else-if="service.auditStatus === 'banned'">
              <el-button size="small" @click="viewService(service)">查看</el-button>
              <el-button size="small" type="primary" @click="appealService(service)">申诉</el-button>
            </template>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 发布/编辑服务对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingService ? '编辑服务' : '发布新服务'"
      width="600px"
      @close="resetServiceForm"
    >
      <el-form
        ref="serviceFormRef"
        :model="serviceForm"
        :rules="serviceRules"
        label-width="100px"
      >
        <el-form-item label="服务类型" prop="type">
          <el-select v-model="serviceForm.type" placeholder="请选择服务类型" style="width: 100%;" @change="handleServiceTypeChange">
            <el-option
              label="洗衣服"
              value="laundry"
              :disabled="!isDepositPaid('laundry')"
            >
              <span>洗衣服</span>
              <span v-if="!isDepositPaid('laundry')" style="color: #f56c6c; font-size: 12px; margin-left: 8px;">
                (需缴纳¥{{ getRequiredDeposit('laundry') }}保证金)
              </span>
            </el-option>
            <el-option
              label="洗鞋"
              value="shoes"
              :disabled="!isDepositPaid('shoes')"
            >
              <span>洗鞋</span>
              <span v-if="!isDepositPaid('shoes')" style="color: #f56c6c; font-size: 12px; margin-left: 8px;">
                (需缴纳¥{{ getRequiredDeposit('shoes') }}保证金)
              </span>
            </el-option>
            <el-option
              label="洗萌宠"
              value="pet"
              :disabled="!isDepositPaid('pet')"
            >
              <span>洗萌宠</span>
              <span v-if="!isDepositPaid('pet')" style="color: #f56c6c; font-size: 12px; margin-left: 8px;">
                (需缴纳¥{{ getRequiredDeposit('pet') }}保证金)
              </span>
            </el-option>
            <el-option
              label="洗包包"
              value="bag"
              :disabled="!isDepositPaid('bag')"
            >
              <span>洗包包</span>
              <span v-if="!isDepositPaid('bag')" style="color: #f56c6c; font-size: 12px; margin-left: 8px;">
                (需缴纳¥{{ getRequiredDeposit('bag') }}保证金)
              </span>
            </el-option>
            <el-option
              label="洗被子"
              value="bedding"
              :disabled="!isDepositPaid('bedding')"
            >
              <span>洗被子</span>
              <span v-if="!isDepositPaid('bedding')" style="color: #f56c6c; font-size: 12px; margin-left: 8px;">
                (需缴纳¥{{ getRequiredDeposit('bedding') }}保证金)
              </span>
            </el-option>
            <el-option
              label="洗车"
              value="car"
              :disabled="!isDepositPaid('car')"
            >
              <span>洗车</span>
              <span v-if="!isDepositPaid('car')" style="color: #f56c6c; font-size: 12px; margin-left: 8px;">
                (需缴纳¥{{ getRequiredDeposit('car') }}保证金)
              </span>
            </el-option>
            <el-option
              label="上门清洗"
              value="home_cleaning"
              :disabled="!isDepositPaid('home_cleaning')"
            >
              <span>上门清洗</span>
              <span v-if="!isDepositPaid('home_cleaning')" style="color: #f56c6c; font-size: 12px; margin-left: 8px;">
                (需缴纳¥{{ getRequiredDeposit('home_cleaning') }}保证金)
              </span>
            </el-option>
            <el-option
              label="疏通厕所"
              value="plumbing"
              :disabled="!isDepositPaid('plumbing')"
            >
              <span>疏通厕所</span>
              <span v-if="!isDepositPaid('plumbing')" style="color: #f56c6c; font-size: 12px; margin-left: 8px;">
                (需缴纳¥{{ getRequiredDeposit('plumbing') }}保证金)
              </span>
            </el-option>
          </el-select>

          <!-- 保证金状态提示 -->
          <div class="deposit-status-info" style="margin-top: 8px;">
            <div v-if="serviceForm.type && isDepositPaid(serviceForm.type)" class="deposit-paid">
              <el-icon style="color: #67c23a;"><Check /></el-icon>
              <span style="color: #67c23a; font-size: 12px; margin-left: 4px;">
                已缴纳¥{{ getRequiredDeposit(serviceForm.type) }}保证金，可以发布此服务
              </span>
            </div>
            <div v-else-if="serviceForm.type" class="deposit-unpaid">
              <el-icon style="color: #f56c6c;"><Warning /></el-icon>
              <span style="color: #f56c6c; font-size: 12px; margin-left: 4px;">
                需要先缴纳¥{{ getRequiredDeposit(serviceForm.type) }}保证金才能发布此服务
              </span>
              <el-button
                type="primary"
                size="small"
                style="margin-left: 8px;"
                @click="goToDepositPage"
              >
                去缴纳保证金
              </el-button>
            </div>
          </div>

          <div class="service-type-info" v-if="serviceForm.type">
            <div class="deposit-desc" style="margin-top: 8px; color: #909399; font-size: 12px;">
              {{ getServiceDescription(serviceForm.type) }}
            </div>
          </div>
        </el-form-item>

        <el-form-item label="服务名称" prop="name">
          <el-input v-model="serviceForm.name" placeholder="请输入服务名称" maxlength="30" show-word-limit />
        </el-form-item>

        <el-form-item label="服务描述" prop="description">
          <el-input
            v-model="serviceForm.description"
            type="textarea"
            placeholder="请详细描述您的服务内容、特色和优势"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="服务价格" prop="price">
              <el-input-number
                v-model="serviceForm.price"
                :min="0"
                :precision="2"
                controls-position="right"
                style="width: 100%;"
                placeholder="0.00"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计价单位" prop="unit">
              <el-select v-model="serviceForm.unit" placeholder="请选择计价单位" style="width: 100%;">
                <el-option label="件" value="件" />
                <el-option label="双" value="双" />
                <el-option label="只" value="只" />
                <el-option label="套" value="套" />
                <el-option label="次" value="次" />
                <el-option label="小时" value="小时" />
                <el-option label="平方米" value="平方米" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最远到达时长" prop="duration">
              <el-input-number
                v-model="serviceForm.duration"
                :min="0.5"
                :max="168"
                :step="0.5"
                controls-position="right"
                style="width: 100%;"
                placeholder="小时"
              />
              <div class="duration-tips">
                <span>到达最远服务区域的时间</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="服务区域" prop="serviceArea">
          <div class="service-area-selector">
            <el-cascader
              v-model="serviceForm.serviceAreaCodes"
              :options="areaOptions"
              :props="cascaderProps"
              placeholder="请选择服务区域"
              style="width: 100%;"
              @change="handleAreaChange"
              multiple
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="2"
            />
            <div class="area-tips">
              <el-icon><InfoFilled /></el-icon>
              <span>可选择多个区域，支持省、市、区县、街道级别选择</span>
            </div>
          </div>
        </el-form-item>

        <!-- 服务图片上传 -->
        <el-form-item label="服务图片" prop="images">
          <div class="image-upload-section">
            <div class="upload-tips">
              <el-icon><Picture /></el-icon>
              <span>上传服务图片，让客户更直观地了解您的服务（建议4-10张）</span>
            </div>

            <el-upload
              ref="uploadRef"
              v-model:file-list="serviceForm.images"
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :limit="10"
              :on-exceed="handleExceed"
              accept="image/*"
              multiple
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <div class="upload-guidelines">
              <h4>图片要求：</h4>
              <ul>
                <li>• 图片格式：JPG、PNG、WEBP</li>
                <li>• 图片大小：不超过5MB</li>
                <li>• 图片数量：4-10张（建议6-8张）</li>
                <li>• 图片内容：展示服务过程、效果对比、工具设备等</li>
                <li>• 第一张图片将作为封面图显示</li>
              </ul>
            </div>
          </div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="免费上门取货" prop="freePickup">
              <el-radio-group v-model="serviceForm.freePickup">
                <el-radio :label="true">免费上门取货</el-radio>
                <el-radio :label="false">不提供上门取货</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否支持预约" prop="supportBooking">
              <el-radio-group v-model="serviceForm.supportBooking">
                <el-radio :label="true">支持预约</el-radio>
                <el-radio :label="false">不支持预约</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="serviceSubmitting" @click="submitService">
          {{ editingService ? '保存修改' : '发布服务' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewDialogVisible" title="图片预览" width="800px">
      <img :src="previewImageUrl" alt="预览图片" style="width: 100%; max-height: 500px; object-fit: contain;" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Star,
  Timer,
  List,
  Wallet,
  User,
  Tools,
  Check,
  Warning,
  Picture,
  Document,
  Clock,
  Close,
  InfoFilled
} from '@element-plus/icons-vue'
import { getServiceStats, getDepositStatusList } from '@/api/services'

const router = useRouter()
const dialogVisible = ref(false)
const serviceSubmitting = ref(false)
const editingService = ref(null)
const serviceFormRef = ref(null)
const filterStatus = ref('')
const filterType = ref('')
const filterAuditStatus = ref('')
const uploadRef = ref(null)
const previewDialogVisible = ref(false)
const previewImageUrl = ref('')

// 服务统计
const serviceStats = reactive({
  draft: 0,        // 草稿箱
  pending: 0,      // 审核中
  approved: 0,     // 已通过
  rejected: 0,     // 被驳回
  banned: 0,       // 被封禁
  active: 0,       // 已上架
  inactive: 0,     // 已下架
  totalOrders: 0,
  totalRevenue: 0
})

// 已缴纳保证金的服务类型（从保证金管理页面获取）
const paidServiceTypes = ref([])

// 区域选择配置
const cascaderProps = {
  value: 'code',
  label: 'name',
  children: 'children',
  multiple: true,
  checkStrictly: false
}

// 区域数据（从API获取）
const areaOptions = ref([])

const services = ref([])

// 计算属性
const filteredServices = computed(() => {
  return services.value.filter(service => {
    const statusMatch = !filterStatus.value || service.status === filterStatus.value
    const typeMatch = !filterType.value || service.type === filterType.value
    const auditStatusMatch = !filterAuditStatus.value || service.auditStatus === filterAuditStatus.value
    return statusMatch && typeMatch && auditStatusMatch
  })
})

const serviceForm = reactive({
  type: '',
  name: '',
  description: '',
  price: 0,
  unit: '件',
  serviceArea: '',
  serviceAreaCodes: [],
  duration: 24,
  freePickup: true,
  supportBooking: true,
  images: []
})

// 表单验证规则
const serviceRules = {
  type: [
    { required: true, message: '请选择服务类型', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入服务名称', trigger: 'blur' },
    { min: 2, max: 30, message: '服务名称长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入服务描述', trigger: 'blur' },
    { min: 10, max: 200, message: '服务描述长度在 10 到 200 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入服务价格', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请选择计价单位', trigger: 'change' }
  ],
  serviceArea: [
    { required: true, message: '请输入服务区域', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入预计时长', trigger: 'blur' },
    { type: 'number', min: 0.5, max: 168, message: '时长在 0.5 到 168 小时之间', trigger: 'blur' }
  ],
  images: [
    {
      validator: (rule, value, callback) => {
        if (!value || value.length < 4) {
          callback(new Error('请至少上传4张服务图片'))
        } else if (value.length > 10) {
          callback(new Error('最多只能上传10张图片'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 方法
const getServiceIcon = (type) => {
  const iconMap = {
    'laundry': 'User',
    'shoes': 'Star',
    'pet': 'Timer',
    'bag': 'List',
    'bedding': 'Star',
    'car': 'Star',
    'home_cleaning': 'Tools',
    'plumbing': 'Tools'
  }
  return iconMap[type] || 'Star'
}

const getServiceIconClass = (type) => {
  const classMap = {
    'laundry': 'icon-laundry',
    'shoes': 'icon-shoes',
    'pet': 'icon-pet',
    'bag': 'icon-bag',
    'bedding': 'icon-bedding',
    'car': 'icon-car',
    'home_cleaning': 'icon-home',
    'plumbing': 'icon-plumbing'
  }
  return classMap[type] || 'icon-default'
}

// 保证金相关方法
const getRequiredDeposit = (serviceType) => {
  const depositMap = {
    'laundry': 500,      // 洗衣服
    'shoes': 300,        // 洗鞋
    'pet': 1000,         // 洗萌宠
    'bag': 400,          // 洗包包
    'bedding': 600,      // 洗被子
    'car': 800,          // 洗车
    'home_cleaning': 1200, // 上门清洗
    'plumbing': 1500     // 疏通厕所
  }
  return depositMap[serviceType] || 0
}

const getServiceDescription = (serviceType) => {
  const descMap = {
    'laundry': '基础洗护服务，风险较低',
    'shoes': '鞋类清洗服务，需要专业技能',
    'pet': '宠物护理服务，需要专业资质和经验',
    'bag': '包包清洗护理，需要细致操作',
    'bedding': '大件床品清洗，需要专业设备',
    'car': '汽车清洗服务，需要专业工具',
    'home_cleaning': '上门清洁服务，服务范围广泛',
    'plumbing': '管道疏通服务，技术要求高'
  }
  return descMap[serviceType] || ''
}

const handleServiceTypeChange = (value) => {
  if (value && !isDepositPaid(value)) {
    const requiredDeposit = getRequiredDeposit(value)
    ElMessage.warning(`该服务类型需要先缴纳 ¥${requiredDeposit} 保证金才能发布`)
  }
}

// 跳转到保证金管理页面
const goToDepositPage = () => {
  router.push('/main/deposit')
}

// 跳转到推广管理页面
const goToPromotion = (service) => {
  router.push('/main/promotion')
  ElMessage.info(`查看 "${service.name}" 的推广数据`)
}

// 处理区域选择变化
const handleAreaChange = (value) => {
  if (value && value.length > 0) {
    // 将选中的区域代码转换为文本描述
    const areaNames = []
    value.forEach(codes => {
      if (Array.isArray(codes) && codes.length > 0) {
        const areaName = getAreaNameByCodes(codes)
        if (areaName) {
          areaNames.push(areaName)
        }
      }
    })
    serviceForm.serviceArea = areaNames.join('、')
  } else {
    serviceForm.serviceArea = ''
  }
}

// 根据区域代码获取区域名称
const getAreaNameByCodes = (codes) => {
  let current = areaOptions.value
  let names = []

  for (let i = 0; i < codes.length; i++) {
    const code = codes[i]
    const found = current.find(item => item.code === code)
    if (found) {
      names.push(found.name)
      current = found.children || []
    } else {
      break
    }
  }

  return names.join('')
}

const showAddDialog = () => {
  editingService.value = null
  resetServiceForm()
  dialogVisible.value = true
}

// 检查是否已缴纳保证金
const isDepositPaid = (serviceType) => {
  return paidServiceTypes.value.includes(serviceType)
}

// 获取未缴纳保证金的服务类型
const getUnpaidServiceTypes = () => {
  const allServiceTypes = ['laundry', 'shoes', 'pet', 'bag', 'bedding', 'car', 'home_cleaning', 'plumbing']
  return allServiceTypes.filter(type => !paidServiceTypes.value.includes(type))
}

const resetServiceForm = () => {
  if (serviceFormRef.value) {
    serviceFormRef.value.resetFields()
  }
  Object.assign(serviceForm, {
    type: '',
    name: '',
    description: '',
    price: 0,
    unit: '件',
    serviceArea: '',
    serviceAreaCodes: [],
    duration: 24,
    freePickup: true,
    supportBooking: true,
    images: []
  })
}

// 图片上传相关方法
const handlePictureCardPreview = (file) => {
  previewImageUrl.value = file.url || file.response?.url || URL.createObjectURL(file.raw)
  previewDialogVisible.value = true
}

const handleRemove = (file, fileList) => {
  serviceForm.images = fileList
  // 触发表单验证
  if (serviceFormRef.value) {
    serviceFormRef.value.validateField('images')
  }
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  // 创建预览URL
  const url = URL.createObjectURL(file)
  const fileItem = {
    name: file.name,
    url: url,
    raw: file,
    status: 'ready'
  }

  serviceForm.images.push(fileItem)

  // 触发表单验证
  if (serviceFormRef.value) {
    serviceFormRef.value.validateField('images')
  }

  return false // 阻止自动上传
}

const handleExceed = (files, fileList) => {
  ElMessage.warning(`最多只能上传 10 张图片，当前已选择 ${fileList.length} 张，本次选择了 ${files.length} 张`)
}

const editService = (service) => {
  editingService.value = service
  Object.assign(serviceForm, {
    type: service.type,
    name: service.name,
    description: service.description,
    price: service.price,
    unit: service.unit,
    serviceArea: service.serviceArea,
    duration: service.duration,
    freePickup: service.freePickup,
    supportBooking: service.supportBooking,
    images: service.images || []
  })
  dialogVisible.value = true
}

const toggleStatus = async (service) => {
  try {
    const action = service.status === 'active' ? '下架' : '上架'
    await ElMessageBox.confirm(`确认${action}此服务？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const oldStatus = service.status
    service.status = service.status === 'active' ? 'inactive' : 'active'

    // 更新统计
    if (oldStatus === 'active') {
      serviceStats.active--
      serviceStats.inactive++
    } else {
      serviceStats.active++
      serviceStats.inactive--
    }

    ElMessage.success(`服务已${action}`)
  } catch {
    ElMessage.info('已取消操作')
  }
}

const deleteService = async (service) => {
  try {
    await ElMessageBox.confirm('确认删除此服务？删除后无法恢复。', '删除确认', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    })

    const index = services.value.findIndex(s => s.id === service.id)
    if (index > -1) {
      services.value.splice(index, 1)

      // 更新统计
      if (service.status === 'active') {
        serviceStats.active--
      } else {
        serviceStats.inactive--
      }

      ElMessage.success('服务已删除')
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

const submitService = async () => {
  if (!serviceFormRef.value) return

  try {
    await serviceFormRef.value.validate()

    // 验证是否已缴纳保证金
    if (!isDepositPaid(serviceForm.type)) {
      ElMessage.error(`发布${getServiceTypeName(serviceForm.type)}服务需要先缴纳¥${getRequiredDeposit(serviceForm.type)}保证金`)
      return
    }

    serviceSubmitting.value = true

    // 模拟提交
    await new Promise(resolve => setTimeout(resolve, 1000))

    if (editingService.value) {
      // 编辑服务
      const index = services.value.findIndex(s => s.id === editingService.value.id)
      if (index > -1) {
        services.value[index] = {
          ...services.value[index],
          ...serviceForm
        }
      }
      ElMessage.success('服务修改成功')
    } else {
      // 新增服务 - 默认为草稿状态
      const newService = {
        id: Date.now(),
        ...serviceForm,
        status: 'inactive',
        auditStatus: 'draft',
        auditTime: '',
        auditRemark: '',
        orderCount: 0,
        rating: 0,
        revenue: 0,
        // 生成推广链接信息
        linkId: `PL${String(Date.now()).slice(-6)}`,
        promotionUrl: `https://app.laundry.com/service/PL${String(Date.now()).slice(-6)}`
      }
      services.value.push(newService)
      serviceStats.draft++
      ElMessage.success('服务已保存到草稿箱，请提交审核后才能上架')
    }

    dialogVisible.value = false
  } catch (error) {
    console.error('提交服务失败:', error)
  } finally {
    serviceSubmitting.value = false
  }
}

// 获取服务类型名称
const getServiceTypeName = (serviceType) => {
  const nameMap = {
    'laundry': '洗衣服',
    'shoes': '洗鞋',
    'pet': '洗萌宠',
    'bag': '洗包包',
    'bedding': '洗被子',
    'car': '洗车',
    'home_cleaning': '上门清洗',
    'plumbing': '疏通厕所'
  }
  return nameMap[serviceType] || serviceType
}

// 获取审核状态类型
const getAuditStatusType = (auditStatus) => {
  const typeMap = {
    'draft': 'info',
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger',
    'banned': 'danger'
  }
  return typeMap[auditStatus] || 'info'
}

// 获取审核状态文本
const getAuditStatusText = (auditStatus) => {
  const textMap = {
    'draft': '草稿',
    'pending': '审核中',
    'approved': '已通过',
    'rejected': '被驳回',
    'banned': '被封禁'
  }
  return textMap[auditStatus] || '未知'
}

// 提交审核
const submitForReview = async (service) => {
  try {
    await ElMessageBox.confirm(
      '确认提交此服务进行审核？提交后将无法修改，请确保信息准确。',
      '提交审核',
      {
        confirmButtonText: '确认提交',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    service.auditStatus = 'pending'
    service.auditTime = ''
    service.auditRemark = ''

    // 更新统计
    if (service.auditStatus === 'draft') {
      serviceStats.draft--
    } else if (service.auditStatus === 'rejected') {
      serviceStats.rejected--
    }
    serviceStats.pending++

    ElMessage.success('已提交审核，请耐心等待审核结果')
  } catch {
    ElMessage.info('已取消提交')
  }
}

// 撤回审核
const withdrawReview = async (service) => {
  try {
    await ElMessageBox.confirm(
      '确认撤回审核？撤回后服务将回到草稿状态。',
      '撤回审核',
      {
        confirmButtonText: '确认撤回',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    service.auditStatus = 'draft'
    service.auditTime = ''
    service.auditRemark = ''

    // 更新统计
    serviceStats.pending--
    serviceStats.draft++

    ElMessage.success('已撤回审核，服务回到草稿状态')
  } catch {
    ElMessage.info('已取消撤回')
  }
}

// 退回草稿
const moveToDraft = async (service) => {
  try {
    await ElMessageBox.confirm(
      '确认将此服务退回草稿箱？退回后需要重新提交审核。',
      '退回草稿',
      {
        confirmButtonText: '确认退回',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const oldAuditStatus = service.auditStatus
    service.auditStatus = 'draft'
    service.status = 'inactive'
    service.auditTime = ''
    service.auditRemark = ''

    // 更新统计
    if (oldAuditStatus === 'approved') {
      serviceStats.approved--
    }
    serviceStats.draft++

    if (service.status === 'active') {
      serviceStats.active--
      serviceStats.inactive++
    }

    ElMessage.success('服务已退回草稿箱')
  } catch {
    ElMessage.info('已取消操作')
  }
}

// 查看服务详情
const viewService = (service) => {
  ElMessage.info(`查看服务：${service.name}`)
}

// 申诉服务
const appealService = async (service) => {
  try {
    await ElMessageBox.prompt(
      '请输入申诉理由：',
      '服务申诉',
      {
        confirmButtonText: '提交申诉',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请详细说明申诉理由...'
      }
    )

    ElMessage.success('申诉已提交，我们会在3个工作日内处理')
  } catch {
    ElMessage.info('已取消申诉')
  }
}

// 获取服务统计数据
const fetchServiceStats = async () => {
  try {
    const response = await getServiceStats()
    if (response.code === 200) {
      Object.assign(serviceStats, response.data)
    } else {
      throw new Error(response.message || '获取服务统计失败')
    }
  } catch (error) {
    console.error('获取服务统计失败:', error)
    ElMessage.error(error.message || '获取服务统计失败')
  }
}

// 获取押金状态
const fetchDepositStatus = async () => {
  try {
    const response = await getDepositStatusList()
    if (response.code === 200) {
      const paidTypes = []
      Object.entries(response.data).forEach(([type, isPaid]) => {
        if (isPaid) {
          paidTypes.push(type.toLowerCase())
        }
      })
      paidServiceTypes.value = paidTypes
    } else {
      throw new Error(response.message || '获取押金状态失败')
    }
  } catch (error) {
    console.error('获取押金状态失败:', error)
    ElMessage.error(error.message || '获取押金状态失败')
  }
}

onMounted(async () => {
  console.log('服务管理页面已加载')
  await fetchServiceStats()
  await fetchDepositStatus()
})
</script>

<style scoped>
.services-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

/* 统计区域 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-card.active .stat-icon {
  background: linear-gradient(135deg, #10b981, #059669);
}

.stat-card.inactive .stat-icon {
  background: linear-gradient(135deg, #6b7280, #4b5563);
}

.stat-card.orders .stat-icon {
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
}

.stat-card.revenue .stat-icon {
  background: linear-gradient(135deg, #f59e0b, #d97706);
}

.stat-card.draft .stat-icon {
  background: linear-gradient(135deg, #9ca3af, #6b7280);
}

.stat-card.pending .stat-icon {
  background: linear-gradient(135deg, #f59e0b, #d97706);
}

.stat-card.approved .stat-icon {
  background: linear-gradient(135deg, #10b981, #059669);
}

.stat-card.rejected .stat-icon {
  background: linear-gradient(135deg, #ef4444, #dc2626);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

/* 服务列表 */
.services-list-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-filters {
  display: flex;
  align-items: center;
}

.services-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  padding: 10px 0;
}

.service-card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 20px;
  background: white;
  transition: all 0.3s ease;
  position: relative;
}

.service-card:hover {
  border-color: #3b82f6;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.1);
  transform: translateY(-2px);
}

.service-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.service-type-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.service-type-icon.icon-laundry {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.service-type-icon.icon-shoes {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.service-type-icon.icon-pet {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.service-type-icon.icon-bag {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.service-type-icon.icon-bedding {
  background: linear-gradient(135deg, #fa709a, #fee140);
}

.service-type-icon.icon-car {
  background: linear-gradient(135deg, #a8edea, #fed6e3);
}

.service-type-icon.icon-home {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
}

.service-type-icon.icon-plumbing {
  background: linear-gradient(135deg, #89f7fe, #66a6ff);
}

.service-type-icon.icon-default {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.service-content h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #1f2937;
  font-weight: 600;
}

.service-description {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: #6b7280;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.service-details {
  margin-bottom: 16px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.detail-item .label {
  color: #6b7280;
}

.detail-item .value {
  color: #1f2937;
  font-weight: 500;
}

.detail-item .value.link-id {
  color: #3b82f6;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  background: #eff6ff;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 服务区域选择器样式 */
.service-area-selector {
  .area-tips {
    display: flex;
    align-items: center;
    margin-top: 8px;
    padding: 8px 12px;
    background: #f0f9ff;
    border: 1px solid #e0f2fe;
    border-radius: 6px;
    font-size: 12px;
    color: #0369a1;

    .el-icon {
      margin-right: 6px;
      color: #0284c7;
    }
  }
}

/* 时长提示样式 */
.duration-tips {
  margin-top: 4px;
  font-size: 12px;
  color: #6b7280;
}

.detail-item .price {
  color: #059669;
  font-weight: 600;
  font-size: 16px;
}

.service-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-number {
  display: block;
  font-size: 16px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 2px;
}

.stat-text {
  font-size: 12px;
  color: #6b7280;
}

.service-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

/* 添加服务卡片 */
.add-service-card {
  border: 2px dashed #d1d5db;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 300px;
}

.add-service-card:hover {
  border-color: #3b82f6;
  background: #eff6ff;
  transform: translateY(-2px);
}

.add-service-content {
  text-align: center;
}

.add-icon {
  font-size: 48px;
  color: #9ca3af;
  margin-bottom: 12px;
}

.add-text {
  font-size: 16px;
  color: #374151;
  font-weight: 500;
  margin-bottom: 4px;
}

.add-desc {
  font-size: 14px;
  color: #6b7280;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .services-management {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .stats-section .el-col {
    margin-bottom: 16px;
  }

  .services-grid {
    grid-template-columns: 1fr;
  }

  .header-filters {
    flex-direction: column;
    gap: 8px;
  }
}

:deep(.el-card__header) {
  background: #fafbfc;
  border-bottom: 1px solid #e5e7eb;
  border-radius: 12px 12px 0 0;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.stat-card .el-card__body) {
  padding: 0;
}

/* 保证金状态提示样式 */
.deposit-status-info {
  margin-top: 8px;
}

.deposit-paid {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 6px;
}

.deposit-unpaid {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: 6px;
}

/* 审核备注样式 */
.audit-remark {
  margin-top: 12px;
  padding: 12px;
  background: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: 8px;
}

.remark-label {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
  font-size: 12px;
  color: #ef4444;
  font-weight: 500;
}

.remark-label .el-icon {
  margin-right: 4px;
}

.remark-content {
  font-size: 12px;
  color: #6b7280;
  line-height: 1.5;
}

/* 服务类型选择器样式优化 */
:deep(.el-select-dropdown__item.is-disabled) {
  color: #c0c4cc;
  cursor: not-allowed;
}

:deep(.el-select-dropdown__item.is-disabled span) {
  color: #c0c4cc;
}
</style>
